package com.trsj.lnsj.util;

import java.security.Key;
import java.util.Date;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JWTHelper {

  private static Logger log = LoggerFactory.getLogger(JWTHelper.class);

  // 使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
  public static String createJavaWebToken(Map<String, Object> claims, long expireTime,
      String signKey) {
    return createJavaWebToken(claims, new Date(System.currentTimeMillis() + expireTime), signKey);
  }

  // 该方法使用HS256算法和Secret:bankgl生成signKey
  // 使用HS256签名算法和生成的signingKey最终的Token,claims中是有效载荷
  public static String createJavaWebToken(Map<String, Object> claims, Date expireDate,
      String signKey) {
    return Jwts.builder().setClaims(claims)
        .signWith(SignatureAlgorithm.HS256, getKeyInstance(signKey)).setExpiration(expireDate)
        .compact();
  }

  private static Key getKeyInstance(String signKey) {
    // We will sign our JavaWebToken with our ApiKey secret
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(signKey);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    return signingKey;
  }

  // 解析Token，同时也能验证Token，当验证失败返回null
  public static Map<String, Object> parseJavaWebToken(String jwt, String signKey) {
    try {
      Map<String, Object> jwtClaims =
          Jwts.parser().setSigningKey(getKeyInstance(signKey)).parseClaimsJws(jwt).getBody();
      return jwtClaims;
    } catch (Exception e) {
      log.error("json web token verify failed");
      return null;
    }
  }
  

}
